#!/usr/bin/perl -w
use strict;
#Copyright 2011. Jason Weirather.
#This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License v3 or any later version.
if(scalar(@ARGV) != 1) { die "need the legend temp file path\n";}
my $legend_name = shift @ARGV;
open(LF,$legend_name) or die "could not open $legend_name\n";
chomp(my @lines = <LF>);
close LF;
# now we have to make some type of a .dot file to generate the legend from
my %legend;
foreach my $line (@lines) {
  my @values = split(/\t/,$line);
  $legend{$values[1]} = $values[0];
}
# now the colors are all the keys and the labels are the values in %legend.
open (LD,">$legend_name.dot") or die "could not open $legend_name.dot\n";
print LD "digraph G {\n";

my $size = scalar(keys %legend);
my $index = 0;
# make some arbitrary assignments
my %node_ids;
my $last;
my $nodenum = 0;
print LD "  node [style = filled, shape = rectangle];\n";

foreach my $keyByValue (keys %legend) {
  $node_ids{$keyByValue} = "node$nodenum";
  print LD "  " . $node_ids{$keyByValue} . ' [color = "' . $keyByValue . '"' . ", label = " . '"' . $legend{$keyByValue} . '"' . "];\n";
  $nodenum++;
}
print LD "  edge [style = invis];\n";
print LD "  ";
foreach my $keyByValue (sort{$legend{$a} cmp $legend{$b}} keys %legend) {
  $index++;
  # this orderes them properly
  #print LD "$keyByValue\t$legend{$keyByValue}\n";
  if($index <= scalar(keys(%legend))) { 
    print LD $node_ids{$keyByValue};   
    if($index < scalar(keys(%legend))) { print LD " -> "; }
  }
  #assign aribrary values to each of the keys in case they are long.
  $last = $keyByValue;
}
###print LD $node_ids{$last} . " [style = invis];\n";
print LD "; }";


close LD;

#finished writing it.  Now do the png

`dot -Tpng -o$legend_name.png $legend_name.dot`;
